package tests;

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;

import parser.Parser;
import parser.ParserException;

import tree.MyTreeFactory;
import tree.Tree;

import lexer.Lexer;
import lexer.Token;
import lexer.TokenType;

public class TestUtil {

	public static final int SECOND = 1000;

	/**
	 * Default timeout for the JUnit Tests.
	 */
	public static final long DEFAULT_TIMEOUT = 5 * SECOND;

	/**
	 * Test the lexer for a given program and given "expected Token Array"
	 * 
	 * @param program
	 * @param expectedTokens
	 */
	public static void testLexer(String program, Token... expectedTokens) {
		Lexer lex = new Lexer(program);
		List<Token> tl = new ArrayList<Token>();
		while (lex.hasNext()) {
			tl.add(lex.next());
		}
		if (tl.size() != expectedTokens.length) {
			throw new AssertionError(
					"Token streams have no identical length. Found: "
							+ tl.size() + " Expected: " + expectedTokens.length);
		}
		for (int i = 0; i < tl.size(); i++) {
			Assert.assertTrue("Type is: " + tl.get(i).getType()
					+ " Type expected: " + expectedTokens[i].getType()
					+ " Text is: " + tl.get(i).getText() + " Text expected: "
					+ expectedTokens[i].getText(), tl.get(i).equals(
					expectedTokens[i]));
		}

	}

	public static void testLexerOnlyTokenTypes(String program, 
			TokenType... expectedTokenTypes) {
		Lexer lex = new Lexer(program);
		int i = 0;
		while (lex.hasNext()) {
			Token help = lex.next();
			Assert.assertTrue("Type is: " + help.getType() + " Expected type is: " + 
					expectedTokenTypes[i], help.getType().equals(expectedTokenTypes[i]));
		}
	}
	
	public static void testParserExpression(String program, String expected)
			throws ParserException {
		Lexer lex = new Lexer(program);
		Parser parser = new Parser(new MyTreeFactory(), lex);
		Tree baum = parser.parseExpr();
		System.out.println(baum);
		Assert.assertEquals(expected, baum.toString());
	}

	public static void testParser(String program, String expected)
			throws ParserException {
		Lexer lex = new Lexer(program);
		Parser parser = new Parser(new MyTreeFactory(), lex);
		Tree baum = parser.parse(false);
		System.out.println(baum);
		Assert.assertEquals(expected, baum.toString());
	}

}
